﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RecruitingApplication.Data_Model;

namespace RecruitingApplication.Services
{
    /// <summary>
    /// Summary description for Upload
    /// </summary>
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.Clear();

            HttpPostedFile file = null;
            bool bSuccess = false;
            string strFile = "";
            string dateAdded = DateTime.Now.ToString("MM/dd/yyyy");
            string category = context.Request["CatName"];
            string userName = "";//TODO: make user dynamic
            int categoryID = Convert.ToInt32(context.Request["CatID"]);
            int appID = Convert.ToInt32(context.Request["AppID"]);

            int newDocID = -1;

            if (context.Request.Files.Count > 0)
            {
                file = context.Request.Files[0];
                strFile = file.FileName;
                byte[] buffer = new byte[file.ContentLength];

                file.InputStream.Read(buffer, 0, file.ContentLength);

                DataAccessLayer.OpenDB();
                newDocID = DataAccessLayer.AddDocument(appID, file.FileName, buffer, categoryID);
                DataAccessLayer.CloseDB();

                bSuccess = true;
            }

            string json = "";

            json = "{";
            json += "\"success\" : \"" + bSuccess.ToString().ToLower() + "\",";
            json += "\"fileName\" : \"" + strFile + "\",";
            json += "\"dateAdded\" : \"" + dateAdded + "\",";
            json += "\"category\" : \"" + category + "\",";
            json += "\"docID\" : \"" + newDocID + "\",";
            json += "\"userName\" : \"" + userName + "\"";
            json += "}";

            context.Response.Write("<textarea>");
            context.Response.Write(json);
            context.Response.Write("</textarea>");
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}